import { CloseOutlined, ReloadOutlined } from '@ant-design/icons';
import { history, useLocation, useModel } from '@umijs/max';
import type { MenuProps } from 'antd';
import { Dropdown, Tabs } from 'antd';
import React, { useEffect, useMemo } from 'react';
import './index.less';

const PageTabs: React.FC = () => {
  const location = useLocation();
  const { initialState } = useModel('@@initialState') as any;
  const {
    tabs,
    activeKey,
    addTab,
    removeTab,
    closeOtherTabs,
    closeAllTabs,
    closeRightTabs,
    refreshTab,
    updateActiveKey,
  } = useModel('pageTabs');

  // 获取菜单数据，用于查找当前路由的标题
  const menuData = initialState?.menuData || [];

  // 递归查找菜单标题
  const findMenuTitle = (menus: any[], path: string): string | null => {
    for (const menu of menus) {
      if (menu.resourceUrl === path) {
        return menu.resourceName;
      }
      if (menu.children && menu.children.length > 0) {
        const title = findMenuTitle(menu.children, path);
        if (title) return title;
      }
    }
    return null;
  };

  // 监听路由变化，自动添加标签
  useEffect(() => {
    const currentPath = location.pathname;
    const queryString = location.search.replace('?', ''); // 去掉问号
    const fullPath = queryString ? `${currentPath}?${queryString}` : currentPath;

    // 过滤掉登录页和404页
    if (currentPath === '/login' || currentPath === '/404' || currentPath === '/') {
      return;
    }

    // 查找菜单标题
    let title = findMenuTitle(menuData, currentPath);

    // 如果菜单中找不到，使用默认标题
    if (!title) {
      title = currentPath.split('/').pop() || '未命名页面';
    }

    // 如果有 query 参数，在标题后添加标识（可选）
    // 例如: "用户管理 (ID:123)"
    let displayTitle = title;
    if (queryString) {
      const params = new URLSearchParams(queryString);
      const id = params.get('id');
      if (id) {
        displayTitle = `${title} (ID:${id})`;
      }
    }

    addTab(currentPath, displayTitle, queryString);
    updateActiveKey(fullPath);
  }, [location.pathname, location.search, menuData, addTab, updateActiveKey]);

  // 点击标签切换路由
  const handleTabChange = (key: string) => {
    history.push(key);
  };

  // 删除标签
  const handleTabEdit = (targetKey: any, action: 'add' | 'remove') => {
    if (action === 'remove') {
      removeTab(targetKey);
    }
  };

  // 右键菜单配置
  const getContextMenuItems = (tabKey: string): MenuProps['items'] => {
    const currentTab = tabs.find((tab) => tab.key === tabKey);
    const tabIndex = tabs.findIndex((tab) => tab.key === tabKey);
    const hasRightTabs = tabIndex < tabs.length - 1;

    return [
      {
        key: 'refresh',
        label: (
          <span>
            <ReloadOutlined style={{ marginRight: 8 }} />
            刷新
          </span>
        ),
        onClick: () => refreshTab(tabKey),
      },
      {
        key: 'close',
        label: (
          <span>
            <CloseOutlined style={{ marginRight: 8 }} />
            关闭
          </span>
        ),
        disabled: !currentTab?.closable,
        onClick: () => removeTab(tabKey),
      },
      {
        type: 'divider',
      },
      {
        key: 'closeOthers',
        label: '关闭其他',
        onClick: () => closeOtherTabs(tabKey),
      },
      {
        key: 'closeRight',
        label: '关闭右侧',
        disabled: !hasRightTabs,
        onClick: () => closeRightTabs(tabKey),
      },
      {
        key: 'closeAll',
        label: '关闭所有',
        onClick: () => closeAllTabs(),
      },
    ];
  };

  // 渲染标签项
  const items = useMemo(() => {
    return tabs.map((tab) => ({
      key: tab.key,
      label: (
        <Dropdown menu={{ items: getContextMenuItems(tab.key) }} trigger={['contextMenu']}>
          <span className="page-tab-label">{tab.title}</span>
        </Dropdown>
      ),
      closable: tab.closable,
    }));
  }, [tabs]);

  if (tabs.length === 0) {
    return null;
  }

  return (
    <div className="page-tabs-container">
      <Tabs
        type="editable-card"
        hideAdd
        activeKey={activeKey}
        onChange={handleTabChange}
        onEdit={handleTabEdit}
        items={items}
        size="small"
        className="page-tabs"
      />
    </div>
  );
};

export default PageTabs;
